<?php

namespace app\admin\controller\mrbs;

use app\common\controller\Backend;

/**
 * 房间管理
 *
 * @icon fa fa-circle-o
 */
class Room extends Backend
{

    /**
     * MrbsRoom模型对象
     * @var \addons\mrbs\model\Room
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model      = new \addons\mrbs\model\Room;
        $this->facilities = new \addons\mrbs\model\Facilities;
        $this->weeks      = new \addons\mrbs\model\RoomWeeks;
        $this->times      = new \addons\mrbs\model\RoomTimes;
        $this->view->assign("statusList", $this->model->getStatusList());
        //会议室类型
        $this->view->assign("roomTypeList", $this->model->getRoomTypeList());
    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total                                       = $this->model
                ->with(['edifice'])
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->with(['edifice'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as &$row) {
                $row['facilities_list'] = $this->facilities->where('id', 'in', $row['facilities'])->column('name');
            }
            $list   = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try
                {
                    $weeks = $params['weeks'];
                    $times = $params['times'];
                    unset($params['weeks']);
                    unset($params['times']);
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false) {
                        // 更新开放周期
                        if ($weeks) {
                            $this->updateWeeks($this->model->id, $weeks);
                        }
                        // 更新开放时间
                        if ($times) {
                            $this->updateTimes($this->model->id, $times);
                        }
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        // 获取设施列表
        $facilities = $this->facilities->select();
        $this->assign('facilities', $facilities);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try
                {
                    $weeks = $params['weeks'];
                    $times = $params['times'];
                    unset($params['weeks']);
                    unset($params['times']);
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        // 更新开放周期
                        if ($weeks) {
                            $this->updateWeeks($row->id, $weeks);
                        }
                        // 更新开放时间
                        if ($times) {
                            $this->updateTimes($row->id, $times);
                        }
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        // 获取设施列表
        $facilities = $this->facilities->select();
        $this->assign('facilities', $facilities);
        // 开放周期
        $res = $this->weeks->where('room_id', $row['id'])->select();
        $this->assign('weeks', array_column($res, 'week'));
        // 开放时间
        $res = $this->times->field("concat(time,'-',time_stage) as time")->where('room_id', $row['id'])->select();

        $this->assign('times', array_column($res, 'time'));
        return $this->view->fetch();
    }

    /**
     * 更新开放周期
     * @param  [type] $room_id [description]
     * @param  array  $weeks   [description]
     * @return [type]          [description]
     */
    private function updateWeeks($room_id, $weeks = [])
    {
        $this->weeks->where('room_id', $room_id)->delete();
        $datas = [];
        foreach ($weeks as $key => $value) {
            $datas[] = [
                'room_id' => $room_id,
                'week'    => $value,
            ];
        }
        return $this->weeks->insertAll($datas);
    }

    /**
     * 更新开放时间
     * @param  [type] $room_id [description]
     * @param  array  $times   [description]
     * @return [type]          [description]
     */
    private function updateTimes($room_id, $times = [])
    {
        $this->times->where('room_id', $room_id)->delete();
        $datas = [];
        foreach ($times as $key => $value) {
           $roomTimes =  explode("-",$value);
            $datas[] = [
                'room_id' => $room_id,
                'time'    => $roomTimes[0],
                'time_stage' => isset($roomTimes[1]) ? $roomTimes[1] : 0
            ];
        }
        return $this->times->insertAll($datas);
    }
}
